import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Divider, Switch, Select, Input, InputNumber } from 'antd';
import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table/lib/Table';
import { SorterResult } from 'antd/es/table/interface';
import { Target, TargetEnum, RequestType } from '@/common/constants';
import { CategorySelect } from '@/components/Category';
import UploadFile from '@/components/FileUpload';

import CreateForm from './components/CreateForm';
import { FormData } from './data';
import { queryRule, updateRule, addRule, removeRule } from './service';

const { Option } = Select;


const fileProps = (item: any) =>
  item.initialValue ? { fileName: [{ url: item.initialValue, name: item.initialValue }] } : {};

const defaultFormData = {
  url: '',
  name: '',
  type: 'navigateTo',
  icon: '',
  target: '',
  category_id: undefined,
  status: 0,
  sort: 0
};

/**
 * 添加节点
 * @param fields
 */
const handle = async (fields: any, id: any) => {
  const isAdd = !id;
  const txt = isAdd ? '添加' : '编辑';
  const hide = message.loading(`正在${txt}`);
  const params = { ...fields };
  if (params.target === TargetEnum.SCAN) {
    Object.assign(params, { type: RequestType.SCAN })
  }

  if (params.target === TargetEnum.CATE) {
    Object.assign(params, { param: `id=${params.category_id}` });
  }

  Object.assign(params, { status: params.status ? 1 : 0 });
  if (!isAdd) {
    Object.assign(params, { id });
  }
  try {
    if (isAdd) {
      await addRule(params);
    } else {
      delete params.id;
      await updateRule(id, params);
    }
    hide();
    message.success(`${txt}成功`);
    return true;
  } catch (error) {
    hide();
    message.error(`${txt}失败请重试！`);
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: any, action: any) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row: any) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    action.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<FormData>(defaultFormData);
  // const [type, setType] = useState<string>('navigateTo');

  const [target, setTarget] = useState<string>(defaultFormData.target);
  const actionRef = useRef<ActionType>();

  const columns: any[] = [
    {
      title: '名称',
      dataIndex: 'name',
      labelCol: { span: 6 },
      rules: [
        {
          required: true,
          message: '名称为必填项',
        },
      ],
      initialValue: stepFormValues.name,
    },
    {
      title: '跳转类型',
      dataIndex: 'target',
      labelCol: { span: 6 },
      hideInSearch: true,
      rules: [{ required: true, message: '必选' }],
      renderFormItem: (_, item) => {
        return (
          <Select
            placeholder="请选择跳转类型"
            onChange={(v) => {
              console.log(v, 'vvv')
              setTarget(v);
              console.log(item, 'item');
              // onChange(v);
            }}>
            {
              Object.keys(Target).map((it) => {
                return (
                  <Select.Option key={it} value={it}>
                    {Target[it]}
                  </Select.Option>
                )
              })
            }
          </Select>
        )
      },
      render: (text, { target }) => target ? Target[target] : '-',
      initialValue: stepFormValues.target

    },
    {
      title: '分类',
      dataIndex: 'category_id',
      hideInForm: !(target === 'CATE'),
      labelCol: { span: 6 },
      hideInSearch: true,
      hideInTable: true,
      rules: [{ required: true, message: '必选' }],
      renderFormItem: () => {
        return <CategorySelect placeholder={`请选择分类`} />
      },
      initialValue: stepFormValues.category_id
    },
    {
      title: '参数',
      dataIndex: 'param',
      labelCol: { span: 6 },
      hideInSearch: true,
      hideInForm: true,
      rules: [{ required: true, message: '参数必填' }],
      renderFormItem: (_, { onChange }) => {
        return (
          <Input.TextArea rows={3} onChange={onChange}></Input.TextArea>
        )
      },
      hideInTable: true,
      initialValue: stepFormValues.param
    },
    {
      title: '跳转地址',
      dataIndex: 'url',
      labelCol: { span: 6 },
      hideInSearch: true,
      hideInForm: !(target === 'PAGES'),
      rules: [{ required: true, message: '必选' }],
      render: (v) => v || '-',
      initialValue: stepFormValues.url
    },
    {
      title: '图标',
      dataIndex: 'icon',
      labelCol: { span: 6 },
      hideInSearch: true,
      rules: [
        {
          required: true,
          message: '图标为必填项',
        },
      ],
      initialValue: stepFormValues.icon,
      render: (val) =>
        val && <img alt="图标" src={val} style={{ width: 50, height: 50 }} />,
      renderFormItem: (item) => {
        const uploadProps = fileProps(item);
        return <UploadFile {...uploadProps} />;
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      labelCol: { span: 6 },
      rules: [
        {
          required: true,
          message: '排序为必填项',
        },
      ],
      hideInSearch: true,
      initialValue: stepFormValues.sort,
      renderFormItem: () => <InputNumber placeholder="请输入排序" />
    },
    {
      title: '是否显示',
      dataIndex: 'status',
      rules: [],
      initialValue: stepFormValues.status,
      render: (v) => (v === 1 ? '是' : '否'),
      labelCol: { span: 6 },
      hideInSearch: true,
      renderFormItem: (item) => {
        const checkProps = item.initialValue ? { defaultChecked: !!item.initialValue } : {};
        return <Switch {...checkProps} />;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, index, action) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
              setTarget(record.target);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              await handleRemove([record], action);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<any>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<any>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{}}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setStepFormValues(defaultFormData)
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          const ans = {
            ...params,
            page: params?.current,
          };
          if(ans?.name?.length === 0) {
            delete ans?.name;
          }
          delete ans?.current;
          delete ans?._timestamp;
          console.log(ans, 'ans')
          const { data } = await queryRule(ans);
          data.data = data.list;
          return data;
        }}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        id={stepFormValues.id}
      >
        <ProTable<any, any>
          onSubmit={async (value) => {
            const success = await handle(value, stepFormValues.id);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
    </PageHeaderWrapper>
  );
};

export default TableList;
